import { memo, useMemo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Button, Form, Upload, UploadFile, UploadProps } from 'antd';
import { API_BASEURL } from '@/constants/api';
import { authStore } from '@/store/authStore';
import { UploadOutlined } from '@ant-design/icons';
import { useRecoilValue } from 'recoil';

const UploadImage: FC<PropsWithChildren<{ name?: string; label?: string }>> = ({  name,
  label,children
}) => {
  const auth = useRecoilValue(authStore);
  const [fileList, setFileList] = useState<UploadFile[]>([]);


  const props: UploadProps = {
    name: 'file',
    action: API_BASEURL + '/upload',
    method: 'POST',
    listType: 'picture',
    headers: {
      authorization: 'Bearer ' + auth.token,
    },
    maxCount: 1,
    onChange(info) {
      let newFileList = [...info.fileList];

      newFileList = newFileList.map((file) => {
        if (file.response) {
          file.url = API_BASEURL + '/' + file.response.data[0];
        }
        return file;
      });
      setFileList(newFileList);
    },
  };

  return (
    <Form.Item name={name} label={label} rules={[{ required: true }]}>
      <Upload {...props} fileList={fileList} accept={"image/*"}>
        {children}
      </Upload>
    </Form.Item>
  );
};

export default memo(UploadImage);
